package edu.tjut.tjutcommunity.Interceptor;


import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.TokenExpiredException;
import edu.tjut.tjutcommunity.entity.Message;
import edu.tjut.tjutcommunity.service.UserService;
import edu.tjut.tjutcommunity.utils.JWTUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class UserRequestInterceptor implements HandlerInterceptor {

    @Autowired
    UserService userService;
    private final static Logger logger = LoggerFactory.getLogger(UserRequestInterceptor.class);

    private void responseUtil(HttpServletResponse response, Message msg) throws IOException {
        //重置response
        response.reset();
        //设置编码格式
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(200);
        PrintWriter pw = response.getWriter();
        pw.write(JSON.toJSONString(msg));
        pw.flush();
        pw.close();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //http的header中获得token
        String token = request.getHeader("token");
        //token不存在
        if (token == null || token.equals("")) {
            Message mes = Message.Unauthorized();
            responseUtil(response, mes);
            return false;
        }
        //验证token
        String sub = null;
        try {
            sub = JWTUtils.validateToken(token);
            if (!userService.updateOnlineTime(sub)) {
                responseUtil(response, Message.failed("用户不存在"));
                return false;
            }
        } catch (TokenExpiredException e) {
            responseUtil(response, Message.tokenHasExpired());
            return false;
        } catch (Exception e) {
            responseUtil(response, Message.failed("token解析失败"));
            return false;
        }

        //更新token有效时间 (如果需要更新其实就是产生一个新的token)
        try {
            if (JWTUtils.isNeedUpdate(token)) {
                String newToken = JWTUtils.createToken(sub);
                response.setHeader("token", newToken);
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}